package com.bigdata.movieticketapi.filter;

import com.bigdata.movieticketapi.common.exception.ResponseCode;
import com.bigdata.movieticketapi.common.utils.DataResult;
import com.bigdata.movieticketapi.common.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class TokenFilter implements Filter {

    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private ObjectMapper objectMapper;
    @Value("#{'${filter.config.excludeUrls}'.split(',')}")
    private List<String> excludeUrls;
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String requestUrl = servletRequest.getRequestURI();
        PathMatcher matcher = new AntPathMatcher();
        // 拿配置的白名单接口地址与当前请求地址进行一一匹配，匹配成功说明是白名单接口
        if(excludeUrls.stream().noneMatch(excludeUrls->matcher.match(excludeUrls,requestUrl))){
            String token = servletRequest.getHeader("Authorization");
            if(token == null || !jwtUtil.validateToken(token)){
                DataResult result = DataResult.fail(ResponseCode.TOKEN_ERROR.getCode(), ResponseCode.TOKEN_ERROR.getMessage());
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes(StandardCharsets.UTF_8));
                return;
            }
        }

        filterChain.doFilter(request,response);
    }
}
